﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SharpGL.SceneGraph.Helpers
{
    /// <summary>
    /// The Math Helper provides some additional math functions
    /// </summary>
    public class MathHelper
    {
        /// <summary>
        /// This function is to find out whether an integer is power of 2.
        /// </summary>
        /// <param name="value">Integer value to check.</param>
        /// <returns></returns>
        public static Boolean IsPowerOf2(int value)
        {
            return ((value != 0) && !Convert.ToBoolean(value & (value - 1)));
        }
        
        /// <summary>
        /// This function returns the largest power of two that less or equal than argument.
        /// </summary>
        /// <param name="value"></param>
        /// <returns>The largest power of two that less or equal than value.</returns>
        public static int RoundDownToPowerOf2(int value)
        {
            if (IsPowerOf2(value))
            {
                return value;
            }
            else
            {
                int pow = 0;
                while (value > 0)
                {
                    value >>= 1;
                    pow++;
                }
                return Convert.ToInt32(Math.Pow(2, --pow));
            }
        }
    }
}
